import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import 'font-awesome/css/font-awesome.css'

// 引入接口
import { postRequest } from './utils/api';
import { putRequest } from './utils/api';
import { getRequest } from './utils/api';
import { deleteRequest } from './utils/api';
import { initMenu } from './utils/menu';
import { downloadRequest } from './utils/download';

Vue.config.productionTip = false

Vue.use(ElementUI);

// 添加到原型中
Vue.prototype.postRequest = postRequest;
Vue.prototype.putRequest = putRequest;
Vue.prototype.getRequest = getRequest;
Vue.prototype.deleteRequest = deleteRequest;
Vue.prototype.downloadRequest = downloadRequest;

// 全局前置导航守卫
router.beforeEach((to, from, next) => {
  // 判断用户是否登录
  if(window.sessionStorage.getItem('tokenStr')){
    // 初始化导航栏
    initMenu(router, store);
    if(!window.sessionStorage.getItem('user')){
      // 判断用户信息是否存在
      return getRequest('/login/getUserInfo').then(resp=>{
        if(resp){
          window.sessionStorage.setItem('user', JSON.stringify(resp.obj))
          store.commit('INIT_ADMIN', resp.obj)
          next()
        }
      })
    }
    next();
  }else{
    if(to.path == '/'){
      next()
    }else{
      next('/?redirect='+to.path)
    }
  }
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
